<?php
require_once '../db_connect.php';
require_once '../models/user_address.php';

class UserAddressDAO {
    private $conn;

    public function __construct() {
        $this->conn = $GLOBALS['pdo'];
        if (!$this->conn) {
            die("Ошибка подключения к базе данных.");
        }
    }

    // Добавление новой записи в таблицу UserAddresses
    public function addUserAddress(UserAddress $userAddress) {
        $query = "INSERT INTO UserAddresses (user_id, address) VALUES (?, ?)";
        $stmt = $this->conn->prepare($query);
        $stmt->execute([$userAddress->getUserId(), $userAddress->getAddress()]);

        return $this->conn->lastInsertId();
    }

    // Получение записи по ID
    public function getUserAddressById($id) {
        $query = "SELECT * FROM UserAddresses WHERE id = ?";
        $stmt = $this->conn->prepare($query);
        $stmt->execute([$id]);

        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($row) {
            return new UserAddress(
                $row['id'],
                $row['user_id'],
                $row['address']
            );
        }

        return null;
    }

    // Обновление записи
    public function updateUserAddress(UserAddress $userAddress) {
        $query = "UPDATE UserAddresses SET user_id = ?, address = ? WHERE id = ?";
        $stmt = $this->conn->prepare($query);
        return $stmt->execute([
            $userAddress->getUserId(),
            $userAddress->getAddress(),
            $userAddress->getId()
        ]);
    }

    // Удаление записи по ID
    public function deleteUserAddress($id) {
        $query = "DELETE FROM UserAddresses WHERE id = ?";
        $stmt = $this->conn->prepare($query);
        return $stmt->execute([$id]);
    }

    // Получение всех записей
    public function getAllUserAddresses() {
        $query = "SELECT * FROM UserAddresses";
        $stmt = $this->conn->prepare($query);
        $stmt->execute();

        $userAddressList = [];
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $userAddressList[] = new UserAddress(
                $row['id'],
                $row['user_id'],
                $row['address']
            );
        }

        return $userAddressList;
    }

    public function getAllUserAddressesJson() {
        $userAddressList = $this->getAllUserAddresses();
        $userAddressArray = array_map(function($userAddress) {
            return [
                'id' => $userAddress->getId(),
                'user_id' => $userAddress->getUserId(),
                'address' => $userAddress->getAddress()
            ];
        }, $userAddressList);
    
        return json_encode($userAddressArray);
    }

    // Получение всех адресов для конкретного пользователя
    public function getUserAddressesByUserId($userId) {
        $query = "SELECT * FROM UserAddresses WHERE user_id = ?";
        $stmt = $this->conn->prepare($query);
        $stmt->execute([$userId]);

        $userAddressList = [];
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $userAddressList[] = new UserAddress(
                $row['id'],
                $row['user_id'],
                $row['address']
            );
        }

        return $userAddressList;
    }

    public function getUserAddressesByUserIdJson($userId) {
        $userAddressList = $this->getUserAddressesByUserId($userId);
        $userAddressArray = array_map(function($userAddress) {
            return [
                'id' => $userAddress->getId(),
                'user_id' => $userAddress->getUserId(),
                'address' => $userAddress->getAddress()
            ];
        }, $userAddressList);

        return json_encode($userAddressArray);
    }

    public function addNewUserAddress($userId, $address) {
        if (!$userId || !$address) {
            return ['success' => false, 'message' => 'Необходимы идентификатор пользователя и адрес.'];
        }

        $query = "INSERT INTO UserAddresses (user_id, address) VALUES (?, ?)";
        $stmt = $this->conn->prepare($query);
        $success = $stmt->execute([$userId, $address]);

        if ($success) {
            return ['success' => true, 'message' => 'Адрес успешно добавлен.', 'newId' => $this->conn->lastInsertId()];
        } else {
            return ['success' => false, 'message' => 'Не удалось добавить адрес.'];
        }
    }

    public function updateExistingUserAddress($id, $userId, $address) {
        if (!$id || !$userId || !$address) {
            return ['success' => false, 'message' => 'Необходимы идентификатор адреса, идентификатор пользователя и адрес.'];
        }

        $query = "UPDATE UserAddresses SET user_id = ?, address = ? WHERE id = ?";
        $stmt = $this->conn->prepare($query);
        $success = $stmt->execute([$userId, $address, $id]);

        if ($success) {
            return ['success' => true, 'message' => 'Адрес успешно обновлен.'];
        } else {
            return ['success' => false, 'message' => 'Не удалось обновить адрес.'];
        }
    }
}

if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['action']) && $_GET['action'] === 'getAllUserAddressesJson') {
    $dao = new UserAddressDAO();
    echo $dao->getAllUserAddressesJson();
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['action']) && $_GET['action'] === 'getUserAddressesByUserIdJson' && isset($_GET['userId'])) {
    $userId = $_GET['userId'];
    $dao = new UserAddressDAO();
    echo $dao->getUserAddressesByUserIdJson($userId);
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'deleteMultipleUserAddresses' && !empty($_POST['ids'])) {
    $dao = new UserAddressDAO();
    $ids = explode(',', $_POST['ids']);
    $errors = [];
    $successCount = 0;

    foreach ($ids as $id) {
        $success = $dao->deleteUserAddress(trim($id));

        if ($success) {
            $successCount++;
        } else {
            $errors[] = ['id' => $id, 'message' => 'Не удалось удалить запись.'];
        }
    }

    if ($successCount > 0 && count($errors) === 0) {
        echo json_encode(['success' => true, 'message' => 'Все выбранные записи успешно удалены.']);
    } else {
        echo json_encode(['success' => false, 'errors' => $errors]);
    }
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['action']) && $_GET['action'] === 'getUserAddressById' && isset($_GET['id'])) {
    $id = $_GET['id'];
    $dao = new UserAddressDAO();
    $userAddress = $dao->getUserAddressById($id);

    if ($userAddress) {
        echo json_encode([
            'id' => $userAddress->getId(),
            'user_id' => $userAddress->getUserId(),
            'address' => $userAddress->getAddress()
        ]);
    } else {
        echo json_encode(['error' => 'Запись не найдена']);
    }
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $dao = new UserAddressDAO();
    $response = ['success' => false, 'message' => 'Действие не определено или некорректно'];

    switch ($_POST['action']) {
        case 'addUserAddress':
        case 'addNewUserAddress':
            $user_id = $_POST['user_id'] ?? null;
            $address = $_POST['address'] ?? null;

            if ($user_id && $address) {
                $userAddress = new UserAddress(null, $user_id, $address);
                $newId = $dao->addUserAddress($userAddress);
                if ($newId) {
                    $response = ['success' => true, 'message' => 'Запись добавлена', 'newId' => $newId];
                } else {
                    $response = ['success' => false, 'message' => 'Не удалось добавить адрес'];
                }
            } else {
                $response = ['success' => false, 'message' => 'Необходимы идентификатор пользователя и адрес'];
            }
            break;

        case 'updateUserAddress':
        case 'updateExistingUserAddress':
            $id = $_POST['id'] ?? null;
            $user_id = $_POST['user_id'] ?? null;
            $address = $_POST['address'] ?? null;

            if ($id && $user_id && $address) {
                $userAddress = new UserAddress($id, $user_id, $address);
                $success = $dao->updateUserAddress($userAddress);
                if ($success) {
                    $response = ['success' => true, 'message' => 'Запись обновлена'];
                } else {
                    $response = ['success' => false, 'message' => 'Ошибка при обновлении записи'];
                }
            } else {
                $response = ['success' => false, 'message' => 'Необходимы идентификатор адреса, идентификатор пользователя и адрес'];
            }
            break;

        case 'deleteUserAddress':
            if (isset($_POST['id'])) {
                $id = $_POST['id'];
                $success = $dao->deleteUserAddress($id);

                if ($success) {
                    $response = ['success' => true, 'message' => 'Адрес успешно удален.'];
                } else {
                    $response = ['success' => false, 'message' => 'Не удалось удалить адрес.'];
                }
            } else {
                $response = ['success' => false, 'message' => 'ID адреса не указан.'];
            }
            break;
    }

    echo json_encode($response);
    exit();
}
?>